package org.example;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import javafx.application.Application;
import javafx.geometry.Rectangle2D;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.control.*;
import javafx.scene.layout.BorderPane;
import javafx.scene.paint.Color;
import javafx.stage.Screen;
import javafx.stage.Stage;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.datatransfer.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Optional;
import java.util.Properties;


/**
 * JavaFX App
 */
public class App extends Application {

    private boolean isPlaying = false;
    private static String defaultPath = ""; // Default path value
    private static String defaultFilePath = ""; // Default path value
    private String configFilePath = "tools_work_config.properties";
    private long playingStartTime = 0;

    @Override
    public void start(Stage primaryStage) throws InterruptedException {
        loadConfig(); // Load config file on startup

        BorderPane root = new BorderPane();
        Button playPauseButton = new Button("记录 ▶");
        playPauseButton.setStyle("-fx-background-color: #4c8bf5; -fx-text-fill: white;");
        playPauseButton.setOnAction(e -> {
            if (isPlaying) {
                playPauseButton.setText("记录 ▶");
                playPauseButton.setStyle("-fx-background-color: #4c8bf5; -fx-text-fill: white;");

            } else {
                if (StringUtils.isBlank(defaultPath)) {
                    Alert alert = new Alert(Alert.AlertType.WARNING);
                    alert.setTitle("警告");
                    alert.setHeaderText("这是一个警告弹窗");
                    alert.setContentText("没有设置保存路径！");
                    alert.showAndWait();
                    return;
                }

                playPauseButton.setText("暂停 ■");
                playPauseButton.setStyle("-fx-background-color: #f44336; -fx-text-fill: white;");
                playingStartTime = System.currentTimeMillis();
            }
            isPlaying = !isPlaying;
        });

        root.setCenter(playPauseButton);

        // MenuBar with a Settings menu
        MenuBar menuBar = new MenuBar();
        Menu settingsMenu = new Menu("设置");
        MenuItem setPathItem = new MenuItem("设置路径");
        setPathItem.setOnAction(e -> {
            TextInputDialog dialog = new TextInputDialog(defaultPath);
            dialog.setTitle("设置路径");
            dialog.setHeaderText("请输入路径：");
            Optional<String> result = dialog.showAndWait();
            result.ifPresent(path -> {
                defaultPath = path;
                saveConfig(); // Save config file when path is set
            });
        });
        settingsMenu.getItems().add(setPathItem);

        MenuItem setPathItem2 = new MenuItem("监听路径");
        setPathItem2.setOnAction(e -> {
            TextInputDialog dialog = new TextInputDialog(defaultFilePath);
            dialog.setTitle("设置路径");
            dialog.setHeaderText("请输入（文件）路径：");
            Optional<String> result = dialog.showAndWait();
            result.ifPresent(path -> {
                defaultFilePath = path;
                saveConfig(); // Save config file when path is set
            });
        });
        settingsMenu.getItems().add(setPathItem2);

        menuBar.getMenus().add(settingsMenu);
        root.setTop(menuBar);
        Scene scene = new Scene(root, 200, 150);
        scene.setFill(Color.WHITE);

        // 获取屏幕的大小
        Rectangle2D screenBounds = Screen.getPrimary().getVisualBounds();
        // 设置 Stage 的位置为屏幕右下角
        primaryStage.setX(screenBounds.getMaxX() - scene.getWidth() - 50);
        primaryStage.setY(screenBounds.getMaxY() - scene.getHeight() - 50);

        primaryStage.getIcons().add(new javafx.scene.image.Image ("/tools.png"));
        primaryStage.setTitle("工具箱");
        primaryStage.setOnCloseRequest(event -> System.exit(0));
        primaryStage.setScene(scene);
        primaryStage.show();

        customListenAndRecord();
    }

    private void loadConfig() {
        Properties properties = new Properties();
        try (InputStream input = new FileInputStream(configFilePath)) {
            properties.load(input);
            defaultPath = properties.getProperty("path", "");
            defaultFilePath = properties.getProperty("filepath", "");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void saveConfig() {
        Properties properties = new Properties();
        properties.setProperty("path", defaultPath);
        properties.setProperty("filepath", defaultFilePath);
        try (OutputStream output = new FileOutputStream(configFilePath)) {
            properties.store(output, "ToolBoxApp Config");
            System.out.println("Config file saved successfully.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        launch();
    }


    private void customListenAndRecord() throws InterruptedException {
        String os = System.getProperty("os.name").toLowerCase();
        if (os.contains("mac")) {
            if (StringUtils.isBlank(defaultFilePath)) {
                Alert alert = new Alert(Alert.AlertType.WARNING);
                alert.setTitle("警告");
                alert.setHeaderText("这是一个警告弹窗");
                alert.setContentText("没有设置监听文件路径！");
                alert.showAndWait();
                return;
            }

            Thread thread = new Thread(() -> {
                File file = new File(defaultFilePath);
                long lastModified = file.lastModified();

                String fileText;
                JSONObject jsonObject;
                JSONArray data;
                JSONObject element;
                byte[] imageData;
                while (true) {
                    if (!isPlaying) {
                        try {
                            Thread.sleep(5000); // 每隔1秒轮询一次
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        continue;
                    }

                    long currentModified = file.lastModified();
                    if (currentModified != lastModified) {
                        // 文件内容发生变化，进行逻辑处理
                        try {
                            fileText = FileUtils.readFileToString(file, "UTF-8");
                            jsonObject = JSONObject.parseObject(fileText);
                            data = jsonObject.getJSONArray("data");

                            Long updatePlayingStartTime = data.size() == 0 ? null :
                                    data.getJSONObject(0).getLongValue("updateTime");
                            for (int i = 0; i < data.size(); i++) {
                                element = data.getJSONObject(i);
                                long updateTime = element.getLongValue("updateTime");

                                if (updateTime <= playingStartTime) {
                                    break;
                                }
                                String type = element.getString("type");

                                // 文件
                                if ("file".equals(type)) {

                                } else if ("image".equals(type)) { // 图片
                                    imageData = ImageHelper.ImageBase64ToByteArray(element.getString("data"));
                                    String fileType = ImageHelper.getTypeByBase64(element.getString("data"));
                                    LocalDateTime now = LocalDateTime.now();
                                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss");
                                    String fileName = defaultPath + File.separator + now.format(formatter) + "." + fileType;
                                    FileUtils.writeByteArrayToFile(new File(fileName), imageData);
                                } else {
                                    appendToMarkdownFile(element.getString("data"));
                                }

                            }

                            if (updatePlayingStartTime != null) {
                                playingStartTime = updatePlayingStartTime;
                            }


                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        lastModified = currentModified;
                    }

                    try {
                        fileText = null;
                        jsonObject = null;
                        data = null;
                        element = null;
                        imageData = null;
                        Thread.sleep(3000); // 每隔1秒轮询一次
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
            thread.start();

            return;
        }


        Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
        clipboard.addFlavorListener(new FlavorListener() {
            @Override
            public void flavorsChanged(FlavorEvent e) {
                if (!isPlaying) {
                    return;
                }

                Transferable contents = clipboard.getContents(null);
                if (contents != null && contents.isDataFlavorSupported(DataFlavor.stringFlavor)) {
                    try {
                        String copiedText = (String) contents.getTransferData(DataFlavor.stringFlavor);
                        if (!copiedText.isEmpty()) {
                            appendToMarkdownFile(copiedText);
                        }
                    } catch (UnsupportedFlavorException | IOException ex) {
                        ex.printStackTrace();
                    }
                } else if (contents != null && contents.isDataFlavorSupported(DataFlavor.imageFlavor)) {
                    try {
                        Image image = (Image) contents.getTransferData(DataFlavor.imageFlavor);
                        saveImageToFile(image);
                    } catch (UnsupportedFlavorException | IOException ex) {
                        ex.printStackTrace();
                    }
                }
            }
        });
    }

    private static void appendToMarkdownFile(String text) {
        try {
            FileWriter writer = new FileWriter(defaultPath + File.separator + "copied_text.md", true);
            writer.write(text + "\n____________________分★割★线____________________" + "\n");
            writer.close();
            System.out.println("Copied text appended to copied_text.md");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void saveImageToFile(Image image) {
        try {
            LocalDateTime now = LocalDateTime.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss");
            String fileName = defaultPath + File.separator + now.format(formatter) + ".png";
            BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB);
            Graphics2D bGr = bufferedImage.createGraphics();
            bGr.drawImage(image, 0, 0, null);
            bGr.dispose();
            File outputImageFile = new File( fileName); // Change the folder path as needed
            ImageIO.write(bufferedImage, "png", outputImageFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}